package com.faxsun.controller.uc.entity;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;

import org.apache.commons.net.ntp.NTPUDPClient;
import org.apache.commons.net.ntp.TimeInfo; 
import org.apache.commons.net.ntp.TimeStamp;

public class AssistTool {
	
	public static String parseStrToMd5L32(String str){
		String reStr = null;  
        try {  
            MessageDigest md5 = MessageDigest.getInstance("MD5");  
            byte[] bytes = md5.digest(str.getBytes());  
            StringBuffer stringBuffer = new StringBuffer();  
            for (byte b : bytes){  
                int bt = b&0xff;  
                if (bt < 16){  
                    stringBuffer.append(0);  
                }   
                stringBuffer.append(Integer.toHexString(bt));  
            }  
            reStr = stringBuffer.toString();  
        } catch (NoSuchAlgorithmException e) {  
            e.printStackTrace();  
        }  
        return reStr;  
	}
	
	public static String getApi_sigMD5(String api_key,  String nonce,  String timeStramp, String uuid, String api_secret){
		String str = api_key + nonce + timeStramp +uuid + api_secret;
		return parseStrToMd5L32(str);
	}
	
	/*
	 * timeout : seconds.
	 */
	public static boolean timeoutCheck(Date time, int seconds){
		Date now = getCurrentNetTime();
		if(time.before(now)){
			if(now.getTime() - time.getTime() > seconds * 1000){
				return true;
			}
		}          
		return false;
	}
	
	private static Date getCurrentNetTime(){
		try{  
	        NTPUDPClient timeClient = new NTPUDPClient();  
	        String timeServerUrl = "time-c.nist.gov";  
	        InetAddress timeServerAddress = InetAddress.getByName(timeServerUrl);  
	        TimeInfo timeInfo = timeClient.getTime(timeServerAddress);  
	        TimeStamp timeStamp = timeInfo.getMessage().getTransmitTimeStamp();  
	        return timeStamp.getDate();
		 } catch (UnknownHostException e) {  
	        e.printStackTrace();  
		 } catch (IOException e) {  
	        e.printStackTrace();  
		 }
		 return new Date(System.currentTimeMillis());  
	}
	
}


